﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IMDTO;

namespace IMDAL
{
    public class IMDALAddress
    {
        public int WriteAddress(IMDTOAddress address)
        {
            try
            {
               
                InMedioEntities db = new InMedioEntities();

                int land = int.Parse(address.Country);

                Address ad = (from a in db.Address
                              where (a.Contact == address.Contact && a.Street == address.Street && a.HouseNbr == address.HouseNbr
                                  && a.PostBox == address.PostBox && a.Zip == address.Zip && a.City == address.City && a.Country == land)
                              select a).FirstOrDefault();

                if (ad != null)
                {
                    return ad.idAddress;
                }

                Address add = new Address();
                add.PostBox = address.PostBox;
                add.City = address.City;
                add.Contact = address.Contact;
                add.Country = int.Parse(address.Country);
                add.HouseNbr = address.HouseNbr;
                add.PostBox = address.PostBox;
                add.Street = address.Street;
                add.Zip = address.Zip;
                add.UserCrea = "jk";
                add.TsCrea = DateTime.Now;


                db.AddToAddress(add);
                db.SaveChanges();

                return add.idAddress;

            }
            catch (Exception e)
            {
                
                throw e;
            }
        }

        public IMDTOAddress ReplaceNullAddress(IMDTOAddress address)
        {
            try
            {
                if (address.City == null)
                    address.City = "";
                if (address.Contact == null)
                    address.Contact = "";
                if (address.HouseNbr == null)
                    address.HouseNbr = 0;
                if (address.PostBox == null)
                    address.PostBox = "";
                if (address.Street == null)
                    address.Street = "";
                if (address.Zip == null)
                    address.Zip = "";

                return address;


            }
            catch (Exception e)
            {

                throw e;
            }
        }


    }
}
